package com.xuda.springboot.service.Impl;

import com.xuda.springboot.dao.UserMapper;
import com.xuda.springboot.pojo.User;
import com.xuda.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.nio.charset.StandardCharsets;

/**
 * @author ：程序员徐大大
 * @description：TODO
 * @date ：2022-03-20 19:47
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public void register(User user) {

        User byUserName = userMapper.findByUserName(user.getUsername());
        System.out.println(user.getUsername());
        //判断用户是否存在
        if (!ObjectUtils.isEmpty(byUserName)) throw new RuntimeException("当前用户已经被注册");

        //将密码加密， MD5码的特点：相同字符串多次使用md5加密，加密结果一致
        String newPassword = DigestUtils.md5DigestAsHex(user.getPassword().getBytes(StandardCharsets.UTF_8));
        user.setPassword(newPassword);
        userMapper.save(user);
    }

    //登录
    @Override
    public User login(String username, String password) {
        //根据用户名查询用户
        User user = userMapper.findByUserName(username);
        System.out.println("密码"+user.getPassword());
        if (ObjectUtils.isEmpty(user)) throw new RuntimeException("用户名不正确");
        //比较密码
        String passwordSecret = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
        System.out.println(passwordSecret);
        if (!user.getPassword().equals(passwordSecret)) throw new RuntimeException("密码错误");
        return user;
    }
}
